<template>
  <div class="auth">
    <el-input
      size="small"
      v-model="$route.query.roleName"
      disabled
      style="margin-bottom: 20px;"
    ></el-input>
    <el-tree
      :props="props"
      :data="menu"
      show-checkbox
      node-key="id"
      ref="MenuTree"
      default-expand-all
      :default-checked-keys="CheckedMenuList"
      @check-change="handleCheckChange"
    >
    </el-tree>
    <el-button size="small" type="primary" @click="save">保存</el-button>
    <el-button size="small" @click="claerRoleMenu">取消</el-button>
  </div>
</template>

<script>
import { GetRoleIdMenuApi, doAssignApi } from "@/api/acl/menu";
import { Message } from "element-ui";
export default {
  name: "Auth",
  mounted() {
    // console.log(this.$route.query);
    this.GetRoleIdMenu();
  },
  data() {
    return {
      props: {
        label: "name",
        children: "children"
      },
      // 渲染的数据
      menu: [],

      // 选中的id组成的数组
      CheckedMenuList: []
    };
  },
  methods: {
    // 点击保存
    async save() {
      const { id } = this.$route.query;
      await doAssignApi(id, this.CheckedMenuList.toString());
      Message.success("保存成功");
      this.$router.push({
        name: "Role"
      });
    },

    // 点击取消
    claerRoleMenu() {
      this.$router.push({
        name: "Role"
      });
    },

    // 获取角色权限分配列表
    async GetRoleIdMenu() {
      const { id } = this.$route.query;
      const result = await GetRoleIdMenuApi(id);
      // console.log(result.data.children);
      this.menu = result.data.children;

      // 调用递归
      this.deepMenuId(this.menu);
    },

    // 递归 得到默认选中的数据 然后用数据的id生成一个新的数组
    deepMenuId(list) {
      list.forEach(item => {
        if (item.select && item.level >= 4) {
          this.CheckedMenuList.push(item.id);
        }
        this.deepMenuId(item.children);
      });
    },
    handleCheckChange() {
      // 拿到所有选中节点的key(id)组成的数组  然后赋值给默认选中的id组成的数组
      this.CheckedMenuList = this.$refs.MenuTree.getCheckedKeys();
    }
  }
};
</script>

<style lang="scss" scoped>
.auth {
  margin: 20px;
}
</style>
